<template>
    <div v-loading="isLoading">
        <div class="ml-16px mr-16px content-container">
            <div class="pl-26px pt-10px pb-10px">
                <SecondTabs v-model="activeIndex" @update:model-value="handleTabClick" active-color="">
                    <TabItem label="基本信息" path="" :index="0">
                        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="144px" class="pt-26px">
                            <el-form-item label="公司名称" prop="name">
                                <div class="w-400px"><el-input v-model="ruleForm.name" disabled placeholder="请输入公司名称" /></div>
                            </el-form-item>
                            <el-form-item label="联系人" prop="contact">
                                <div class="w-400px"><el-input v-model="ruleForm.contact" placeholder="请输入联系人" /></div>
                            </el-form-item>
                            <el-form-item label="手机号" prop="mobile">
                                <div class="w-400px"><el-input v-model="ruleForm.mobile" placeholder="请输入手机号" /></div>  
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email">
                                <div class="w-400px"><el-input v-model="ruleForm.email" placeholder="请输入邮箱" /></div>
                            </el-form-item>
                            <el-form-item label="固定电话" prop="tel">
                                <div class="w-400px"><el-input v-model="ruleForm.tel" placeholder="请输入固定电话" /></div>
                            </el-form-item>
                            <el-form-item label="公司网站" prop="web">
                                <div class="w-400px"><el-input v-model="ruleForm.web" placeholder="请输入公司网站" /></div>
                            </el-form-item>
                            <el-form-item label="公司地址" prop="address">
                                <div class="w-400px"><el-input v-model="ruleForm.address" placeholder="请输入公司地址" /></div>
                            </el-form-item>
                            <el-form-item label="所在区域" prop="province">
                                <ProvinceCitySelector ref="provinceCitySelector" v-model:province="ruleForm.province"
                                    v-model:city="ruleForm.city" />
                            </el-form-item>
                            <el-form-item label="上传图片" prop="intro">
                                <div class="flex flex-col">
                                    <div class="flex">
                                        <el-upload id="uploadLogo" class="mr-12px !w-194px upload-image" action=""
                                            :show-file-list="false" :on-success="handleAvatarSuccess"
                                            :before-upload="beforeAvatarUpload">
                                            <img v-if="ruleForm.logo" :src="ruleForm.logo" class="avatar"
                                                @click="isPreview = !isPreview" />
                                            <div class="flex flex-col flex-center text-14px text-#999999 upload-btn"
                                                v-else>
                                                <svg-icon size="30px" icon-class="add-fill"></svg-icon>选择图片
                                            </div>
                                            <svg-icon v-if="ruleForm.logo" size="20px" icon-class="close-circle-fill"
                                                class="del" @click="handleDelImg($event)"></svg-icon>
                                            <svg-icon title="替换图片" v-if="ruleForm.logo" size="20px"
                                                icon-class="refresh-fill" class="replace"
                                                @click="handleReplaceImg('uploadLogo')"></svg-icon>
                                        </el-upload>
                                    </div>
                                    <div class="text-12px text-#999 mt-5px">
                                        上传图片必须为jpg、gif、png格式文件且文件大小不超过3M。请确保上传的照片清晰</div>
                                </div>
                            </el-form-item>
                        </el-form>
                    </TabItem>
                    <TabItem label="认证信息" path="" :index="1">
                        <div class="pl-26px pt-26px pb-10px">
                            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="144px">
                                <el-form-item label="法定代表人" prop="legalPerson">
                                    <div class="w-400px"><el-input v-model="ruleForm.legalPerson" placeholder="请输入法定代表人" /></div>
                                </el-form-item>
                                <el-form-item label="企业类型">
                                    <div class="w-400px">
                                        <el-select v-model="ruleForm.enterpriseType" placeholder="请选择企业类型">
                                            <el-option v-for="item in enterpriseTypes" :label="item.label"
                                                :value="item.value" />
                                        </el-select>
                                    </div>
                                </el-form-item>
                                <el-form-item label="成立日期" prop="contact">
                                    <el-date-picker v-model="ruleForm.createDate" type="date" placeholder="选择日期"
                                        size="default" />
                                </el-form-item>
                                <el-form-item label="注册资金" prop="contact">
                                    <div class="flex items-center w-400px">
                                        <div class="flex items-center w-220px mr-12px">
                                            <el-input v-model="ruleForm.registeredCapital" placeholder="请输入注册资金" />
                                        </div>
                                        <el-select class="flex-1" v-model="ruleForm.fundingUnit">
                                            <el-option label="万元" value="1" />
                                            <el-option label="万美元" value="2" />
                                            <el-option label="元" value="3" />
                                        </el-select>
                                    </div>
                                </el-form-item>
                                <el-form-item label="注册号/统一信用代码" prop="code">
                                    <div class="w-400px"><el-input v-model="ruleForm.code" placeholder="请输入注册号/统一信用代码" /></div>
                                </el-form-item>
                                <el-form-item label="登记机关" prop="organ">
                                    <div class="w-400px"><el-input v-model="ruleForm.organ" placeholder="请输入邮箱" /></div>    
                                </el-form-item>
                                <el-form-item label="营业期限" prop="businessTerm">
                                    <div class="flex items-center w-420px">
                                        <el-date-picker v-model="ruleForm.businessTermBegin" type="date"
                                            placeholder="选择日期" size="default" class="!w-155px mr-10px" />
                                        至
                                        <el-date-picker v-model="ruleForm.businessTermEnd" type="date"
                                            placeholder="选择日期" size="default" class="!w-155px ml-10px mr-10px" />
                                        <el-switch v-model="ruleForm.longTerm" inline-prompt active-text="长期"
                                            inactive-text="否" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="经营范围" prop="range">
                                    <div class="w-400px"><el-input type="textarea" :rows="6" v-model="ruleForm.range" placeholder="请输入经营范围" /></div>   
                                </el-form-item>
                                <el-form-item label="营业执照" prop="intro">
                                    <div class="flex flex-col">
                                        <div class="flex">
                                            <el-upload id="uploadLicense" class="mr-12px !w-194px upload-image"
                                                action="" :show-file-list="false" :on-success="handleLicenseSuccess"
                                                :before-upload="beforeAvatarUpload">
                                                <img v-if="ruleForm.license" :src="ruleForm.license" class="avatar"
                                                    @click="isPreview = !isPreview" />
                                                <div class="flex flex-col flex-center text-14px text-#999999 upload-btn"
                                                    v-else>
                                                    <svg-icon size="30px" icon-class="add-fill"></svg-icon>选择图片
                                                </div>
                                                <svg-icon v-if="ruleForm.license" size="20px"
                                                    icon-class="close-circle-fill" class="del"
                                                    @click="handleDelImg($event)"></svg-icon>
                                                <svg-icon title="替换图片" v-if="ruleForm.license" size="20px"
                                                    icon-class="refresh-fill" class="replace"
                                                    @click="handleReplaceImg('uploadLicense')"></svg-icon>
                                            </el-upload>
                                        </div>
                                        <div class="text-12px text-#999 mt-5px">
                                            上传图片必须为jpg、gif、png格式文件且文件大小不超过3M。请确保上传的照片清晰</div>
                                    </div>
                                </el-form-item>

                            </el-form>
                        </div>
                    </TabItem>
                </SecondTabs>

            </div>
        </div>
        <div class="ml-16px mr-16px mt-16px content-container">
            <div class="flex items-center pl-36px pt-26px pr-26px text-14px font-bold level-2-title">
                公司概况
            </div>
            <div class="pl-26px pt-26px pb-40px">
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="144px">
                    <el-form-item label="主营产品" prop="product">
                        <div class="w-600px"><el-input v-model="ruleForm.product" placeholder="请输入主营产品" /></div> 
                    </el-form-item>
                    <el-form-item label="公司介绍" prop="content">
                        <div class="w-90%">
                            <vue-ueditor-wrap v-model="ruleForm.content" editor-id="companyInfo" :config="editorConfig"
                                :editorDependencies="['ueditor.config.js', 'ueditor.all.js']" />
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="w-full bottom-fix-btn">
            <div class="flex ml-16px mr-16px pl-170px pt-26px pb-26px content-container">
                <el-button type="primary" @click="handleSave">保存</el-button>
                <el-button @click="handleReset">重置</el-button>
            </div>
        </div>
        <!-- <div class="w-full fixed right-0 bottom-0px z-999 bottom-fix-btn">
            <div class="flex ml-216px mr-26px pl-170px pt-26px pb-26px content-container">
                <el-button type="primary">保存</el-button>
                <el-button>重置</el-button>
            </div>
        </div> -->
    </div>
</template>

<script setup lang="ts">
import type { UploadProps, CascaderOption } from 'element-plus'
import { enterpriseTypes } from '@/utils/data'
import { formatDateString } from '@/utils/date'
import SecondTabs from '@/components/Tab/Second.vue'
import TabItem from '@/components/Tab/Item.vue'
import ProvinceCitySelector from '@/components/ProvinceCitySelector/index.vue'
import { getCompanyInfoApi, updateCompanyInfoApi } from '@/api/b2b'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { WarningFilled, SuccessFilled } from '@element-plus/icons-vue'

const activeIndex = ref(0)

const ruleFormRef = ref()

const ruleForm = reactive({
    name: '',
    contact: '',
    mobile: '',
    email: '',
    tel: '',
    web: '',
    address: '',
    logo: '',
    enterpriseType: '',
    createDate: '',
    registeredCapital: '',
    code: '',
    organ: '',
    range: '',
    businessTermBegin: '',
    businessTermEnd: '',
    longTerm: true,
    license: '',
    product: '',
    content: '',
    province: '',
    city: '',
    fundingUnit: '',
    legalPerson:''
})

const provinceCitySelector = ref<InstanceType<typeof ProvinceCitySelector> & ProvinceCitySelectorInstance | null>(null)

const isPreview = ref(false)

const isLoading = ref(false)

const rules = reactive({
    name: [
        { required: true, message: '请输入公司名称', trigger: 'blur' }
    ],
    province: [
        { required: true, message: '请选择省份', trigger: 'change' }
    ],
    product: [
        { required: true, message: '请输入主营产品', trigger: 'blur' }
    ],
})

const editorConfig = {
    // 后端服务地址，后端处理参考
    // https://open-doc.modstart.com/ueditor-plus/backend.html
    serverUrl: import.meta.env.VITE_APP_EDITOR_URL,
    UEDITOR_HOME_URL: '/static/UEditorPlus/',
    UEDITOR_CORS_URL: '/static/UEditorPlus/',
    /* 上传图片配置项 */
    imageActionName: 'uploadFile' /* 执行上传图片的action名称 */,
    imageFieldName: 'file' /* 提交的图片表单名称 */,
    imageMaxSize: 2048000 /* 上传大小限制，单位B */,
    imageAllowFiles: ['.png', '.jpg', '.jpeg', '.gif', '.bmp'] /* 上传图片格式显示 */,
    imageCompressEnable: true /* 是否压缩图片,默认是true */,
    imageCompressBorder: 1600 /* 图片压缩最长边限制 */,
    imageInsertAlign: 'none' /* 插入的图片浮动方式 */,
    imageUrlPrefix: '' /* 图片访问路径前缀 */,
    imagePathFormat: '' /* 上传保存路径,可以自定义保存路径和文件名格式 */,
    serverHeaders: {
        'Authorization': sessionStorage.getItem('X-token')
    },
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    ruleForm.logo = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const validTypes = ['image/jpeg', 'image/gif', 'image/png']
    if (!validTypes.includes(rawFile.type)) {
        ElMessage.error('上传图片必须为 JPG / GIF / PNG 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 3) {
        ElMessage.error('上传图片不能超过 3MB!')
        return false
    }
    return true
}

const handleLicenseSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    ruleForm.license = URL.createObjectURL(uploadFile.raw!)
}

// 将原始数据转换为 CascaderOption 类型
const convertToCascaderOptions = (data: any[]): CascaderOption[] => {
    return data.map(item => ({
        label: item.label,
        value: item.value,
        children: item.children ? convertToCascaderOptions(item.children) : undefined
    }))
}

function handleDelImg(event: MouseEvent) {
    event.stopPropagation()
    confirmMessageBox(WarningFilled, '您确定要删除此图片吗？','','', () => {
        ruleForm.license = ''
    })
}

function handleReplaceImg(id: string) {
    const uploadElement = document.getElementById(id);

    // 判断元素是否存在
    if (uploadElement) {
        uploadElement.click();
    } else {
        console.warn(`Element with id "${id}" not found`);
    }
}


function handleTabClick(val: any) {
    //每次切换的时候重置分页，重新获取数据
    const { index } = val
    activeIndex.value = index

}

async function getCompanyInfo() {
    isLoading.value = true
    const res: ResType = await getCompanyInfoApi()
    if (res.code === 200) {
        isLoading.value = false
        ruleForm.name = res.data.CompanyName,
        ruleForm.contact = res.data.ContactName,
        ruleForm.mobile = res.data.MobileNum,
        ruleForm.email = res.data.Email,
        ruleForm.tel = res.data.TelePhoneNum,
        ruleForm.web = res.data.CompanyUrl,
        ruleForm.address = res.data.Address,
        ruleForm.logo = res.data.CompanyImgUrl,
        ruleForm.enterpriseType = res.data.ComType,
        ruleForm.createDate = res.data.EstablishYear,
        ruleForm.registeredCapital = res.data.RegisteredCapital,
        ruleForm.code = res.data.BusinessLicenceNO,
        ruleForm.organ = res.data.IssueAuthority,
        ruleForm.range = res.data.Business,
        ruleForm.businessTermBegin = formatDateString(res.data.BusinessLicenceStart),
        ruleForm.businessTermEnd = formatDateString(res.data.BusinessLicenceEnd),
        ruleForm.longTerm = true,
        ruleForm.license = res.data.BusinessLicenceImgUrl,
        ruleForm.product = res.data.MainProduct,
        ruleForm.content = res.data.CompanyDetail
        ruleForm.province = res.data.Province
        ruleForm.city = res.data.City
        ruleForm.fundingUnit = res.data.RegisteredCapitalUnit
        ruleForm.legalPerson = res.data.CompanyPerson

        nextTick(() => {
            if (provinceCitySelector.value) {
                provinceCitySelector.value.selectedCity = ruleForm.city
                provinceCitySelector.value.selectedProvince.name = ruleForm.province
            }
        })
    }
}

async function handleSave() {
    try {
        const res: ResType = await updateCompanyInfoApi({
            CompanyName: ruleForm.name,
            ContactName: ruleForm.contact,
            MobileNum: ruleForm.mobile,
            Email: ruleForm.email,
            TelePhoneNum: ruleForm.tel,
            CompanyUrl: ruleForm.web,
            Address: ruleForm.address,
            CompanyImgUrl: ruleForm.logo,
            ComType: ruleForm.enterpriseType,
            EstablishYear: ruleForm.createDate,
            RegisteredCapital: ruleForm.registeredCapital,
            BusinessLicenceNO: ruleForm.code,
            IssueAuthority: ruleForm.organ,
            Business: ruleForm.range,
            BusinessLicenceStart: ruleForm.businessTermBegin,
            BusinessLicenceEnd: ruleForm.businessTermEnd,
            BusinessLicenceImgUrl: ruleForm.license,
            MainProduct: ruleForm.product,
            CompanyDetail: ruleForm.content,
            Province: ruleForm.province,
            City: ruleForm.city,
            RegisteredCapitalUnit: ruleForm.fundingUnit
        })
        if (res.code === 200) {
            confirmMessageBox(SuccessFilled, res.message)
        }
    } catch (error: any) {
        if (error.response && error.response.status === 405){
            confirmMessageBox(WarningFilled, error.response.data.message)
        }
    }
}

function handleReset() {
    Object.assign(ruleForm, {
        contact: '',
        mobile: '',
        email: '',
        tel: '',
        web: '',
        address: '',
        logo: '',
        enterpriseType: '',
        createDate: '',
        registeredCapital: '',
        code: '',
        organ: '',
        range: '',
        businessTermBegin: '',
        businessTermEnd: '',
        longTerm: true,
        license: '',
        product: '',
        content: '',
        province: '',
        city: '',
        fundingUnit: ''
    });
    if (provinceCitySelector.value){
        provinceCitySelector.value.selectedCity = ''
        provinceCitySelector.value.selectedProvince.name = ''
    }
    
}

onMounted(() => {
    getCompanyInfo()
})
</script>

<style lang="scss" scoped>
.bottom-fix-btn {
    border-top: 16px solid var(--mainBg);
}
</style>